import axios from 'axios';
import { Msg } from '@/components/msg'
import store from '@/vuex/store'
import router from '@/router'

/**
 * api接口基本路径
 */
export const API_BASE_URL = process.env.NODE_ENV === 'production' ? 'http://118.24.154.53/api' : 'http://118.24.154.53/api' 

// http request 拦截器
axios.interceptors.request.use(
    config => {
        return config
    }, function (error) {
        return Promise.reject(error)
    }
)

// http response 拦截器
axios.interceptors.response.use(function (response) {
    // token 已过期，重定向到登录页面
    if (response.data.code == 401) {
        // store.dispatch('loginOut')
        // router.replace('/login')
    }
    return response
}, function (error) {
    return Promise.reject(error)
})

const axiosCreate = (type, path, data) => {
    let _token = store.getters.userInfo.token
    let instance = axios.create({
        headers: {
            'Authorization': _token,
        }
    })   

    if (type === 'get') {
        return instance({
            method: type,
            url: API_BASE_URL + path,
            params: data
        })
    } else if (type === 'post') {
        return instance({
            method: type,
            url: API_BASE_URL + path,
            data: data,
            changeOrigin:true
        })
    }
}

const http = (type, path, data) => {
    return new Promise((resolve, reject) => {
        axiosCreate(type, path, data).then(res => {
            resolve(res)
        }).catch(res => {
            Msg.error('发送的响应无效')
            reject(res)
        })
    })
}

/**
 * 项目管理
 * @param {Object} data
 */

// 添加群聊、红包、视频
export const add = (data) => http('post', '/add', data)

/**
 * 删除
 */
export const del = (data) => http('post', '/del', data)

/**
 * 列表
 */
export const list = (data) => http('post', '/list', data)

/**
 * 获取单个信息
 */
export const get = (data) => http('post', '/get', data)
